import React, { useEffect, useState } from 'react';
import { Table, message, Empty, Image } from 'antd';
import type { TablePaginationConfig } from 'antd/es/table';
import { useSelector } from 'react-redux';
import type { RootState } from '../../store';
import { listMyBookBorrows } from '../../api/bookBorrowController';
import Header from '../../components/Header/Header';
import defaultBookCover from "../../assets/s34522268.jpg";

interface BookBorrow {
    id: string;
    bookid: string;
    bookname: string;
    bookImage: string;
    borrowtime: string;
    shouldreturntime: string;
    borrowdays: number;
    status: number;
    createtime: string;
    updatetime: string;
    user: {
        id: string;
        nickName: string;
        email: string;
        avatarUrl: string;
    };
}

type StatusConfig = {
    [key: number]: { text: string; color: string; }
};

const statusConfig: StatusConfig = {
    1: { text: '借阅中', color: 'bg-green-500 text-white' },
    2: { text: '已归还', color: 'bg-green-100 text-green-800' },
    3: { text: '已逾期', color: 'bg-red-100 text-red-800' },
    4: { text: '已续借', color: 'bg-yellow-100 text-yellow-800' },
};

export default function MyBooks() {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<BookBorrow[]>([]);
    const [pagination, setPagination] = useState<TablePaginationConfig>({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const loginUser = useSelector((state: RootState) => state.loginUser);

    const fetchData = async (params: any = {}) => {
        setLoading(true);
        try {
            const response = await listMyBookBorrows({
                bookname: params.bookname || '',
                bookid: params.bookid || 0,
                current: params.current || 1,
                pageSize: params.pageSize || 10,
            });

            if (response.code === 200) {
                setData(response.data.records);
                setPagination({
                    ...pagination,
                    current: response.data.current,
                    pageSize: response.data.size,
                    total: response.data.total,
                });
            }
        } catch (error) {
            console.error('获取借阅记录失败:', error);
            message.error('获取借阅记录失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const handleTableChange = (newPagination: TablePaginationConfig) => {
        fetchData({
            current: newPagination.current,
            pageSize: newPagination.pageSize,
        });
    };

    const columns = [
        {
            title: '序号',
            key: 'index',
            width: 80,
            render: (_: any, __: any, index: number) => {
                // 计算实际序号，考虑分页
                return ((pagination.current || 1) - 1) * (pagination.pageSize || 10) + index + 1;
            },
        },
        {
            title: '图书封面',
            dataIndex: 'bookImage',
            key: 'bookImage',
            width: 100,
            render: (image: string) => (
                <Image
                    src={image}
                    alt="书籍封面"
                    width={60}
                    height={80}
                    fallback={defaultBookCover}
                    className="object-cover rounded"
                />
            ),
        },
        {
            title: '书名',
            dataIndex: 'bookname',
            key: 'bookname',
        },
        {
            title: '借阅时间',
            dataIndex: 'borrowtime',
            key: 'borrowtime',
            render: (text: string) => new Date(text).toLocaleDateString(),
        },
        {
            title: '应还时间',
            dataIndex: 'shouldreturntime',
            key: 'shouldreturntime',
            render: (text: string) => new Date(text).toLocaleDateString(),
        },
        {
            title: '借阅天数',
            dataIndex: 'borrowdays',
            key: 'borrowdays',
            render: (text: number) => `${text}天`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: number) => {
                const config = statusConfig[status] || 
                              { text: '未知状态', color: 'bg-gray-100 text-gray-800' };

                return (
                    <span className={`px-2 py-1 rounded-full text-sm font-medium ${config.color}`}>
                        {config.text}
                    </span>
                );
            },
        },
    ];

    return (
        <>
            <Header />
            <div className="max-w-[1500px] mx-auto p-6">
                <div className="bg-white rounded-lg shadow">
                    <div className="p-6">
                        <h1 className="text-2xl font-bold mb-6">我的借阅</h1>
                        <Table
                            columns={columns}
                            dataSource={data}
                            rowKey="id"
                            pagination={pagination}
                            loading={loading}
                            onChange={handleTableChange}
                            scroll={{ x: 1000 }}
                            locale={{
                                emptyText: (
                                    <Empty
                                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        description={
                                            <span className="text-gray-500">
                                                暂无借阅记录
                                            </span>
                                        }
                                    />
                                )
                            }}
                        />
                    </div>
                </div>
            </div>
        </>
    );
}